import { getAddress } from '@/apis/address'
import {
    defineStore
} from 'pinia'

type initCfgType = {
    cdn: string,
    [key: string]: any
}
export const useAppStore = defineStore('appStore', {
    state: () => ({
        initCfg: {},
        selectedAddr: {}
    }),
    getters: {
        cdnUrl(): string {
            return (this.initCfg as initCfgType)?.cdn ?? ''
        }
    },
    actions: {
        setInitCfg(initCfg: initCfgType) {
            if(initCfg) {
                this.initCfg = initCfg
            }
        },
        setAddr(addr: any) {
            this.selectedAddr = addr
        },

        getDefAddr() {
            getAddress().then((res: any) => {
                if (res.data?.length > 0) {
                    const idx = res.data.findIndex((item:any) => item.def === 1)
                    if (idx > -1) {
                        this.selectedAddr = res.data[idx]
                    } else {
                        this.selectedAddr = res.data[0]
                    }
                }
            })
        }
    }
})